package com.lijy.superseckill.controller;

import com.lijy.superseckill.domain.User;
import com.lijy.superseckill.repository.UserRepository;
import com.lijy.superseckill.result.CodeMsg;
import com.lijy.superseckill.result.Result;
import com.lijy.superseckill.service.SeckillUserService;
import com.lijy.superseckill.service.UserService;
import com.lijy.superseckill.util.UUIDUtil;
import com.lijy.superseckill.validator.ValidatorUtil;
import com.lijy.superseckill.vo.LoginVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.text.DateFormat;
import java.util.*;

@Controller
@RequestMapping("/login")
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private SeckillUserService seckillUserService;

    @RequestMapping("to_login")
    public String hello() {
        return "login";
    }

    @RequestMapping("/uid")
    @ResponseBody
    String uid(HttpSession session) {
        String uid = (String) session.getAttribute("uid");
        if (uid == null) {
            uid = UUIDUtil.uuid();
        }
        session.setAttribute("uid", uid);
        return session.getId();
    }

    @RequestMapping(value = "/first", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> firstResp (HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        request.getSession().setAttribute("request Url", request.getRequestURL());
        map.put("request Url", request.getRequestURL());
        return map;
    }

    @RequestMapping(value = "/sessions", method = RequestMethod.GET)
    @ResponseBody
    public Object sessions (HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        map.put("sessionId", request.getSession().getId());
        map.put("message", request.getSession().getAttribute("request Url"));
        return map;
    }

    @RequestMapping("do_login")
    @ResponseBody
    public Result doLogin(@Valid LoginVO loginVO) {
        logger.info(loginVO.toString());
        // 登录
        seckillUserService.login(loginVO);
        return Result.ok(true);

    }

}
